package com.leetcode;

import ds.ListNode;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No23
 * @description 23. 合并K个升序链表
 * @date 2021/1/26 下午3:32
 */
public class No23 {
    public static void main(String[] args) {
        ListNode l10 = new ListNode(1);
        ListNode l11 = new ListNode(4);
        ListNode l12 = new ListNode(5);
        l10.next = l11;
        l11.next = l12;

        ListNode l20 = new ListNode(1);
        ListNode l21 = new ListNode(3);
        ListNode l22 = new ListNode(4);
        l20.next = l21;
        l21.next = l22;

        ListNode l30 = new ListNode(2);
        ListNode l31 = new ListNode(6);
        l30.next = l31;

        ListNode[] lists = new ListNode[3];
        lists[0] = l10;
        lists[1] = l20;
        lists[2] = l30;

        ListNode res = mergeKLists(lists);
        printListNode(res);


    }

    public static ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length < 1){
            return null;
        }
        int len = lists.length;
        // 分治法
        while (len > 1){
            int k = (len + 1) / 2;
            for (int i = 0; i < len / 2; i++) {
                lists[i] = mergeTwoLists(lists[i],lists[i + k]);
            }
            len = k;
        }
        return lists[0];


    }

    public static ListNode mergeTwoLists(ListNode l1,ListNode l2){
        if(l1 == null && l2 == null){
            return null;
        }
        if(l1 == null || l2 == null){
            return l1 == null ? l2 : l1;
        }
        ListNode res = new ListNode(-1);
        ListNode cur = res;
        while (l1 != null && l2 != null){
            if(l1.val < l2.val){
                cur.next = l1;
                cur = cur.next;
                l1 = l1.next;
            }else{
                cur.next = l2;
                cur = cur.next;
                l2 = l2.next;
            }
        }
        if(l1 != null){
            cur.next = l1;
        }
        if(l2 != null){
            cur.next = l2;
        }
        return res.next;
    }

    public static void printListNode(ListNode l){
        if(l == null){
            System.out.println("empty listnode");
        }else{
            while (l != null){
                System.out.print(l.val);
                System.out.print( " ");
                l = l .next;
            }
        }
    }

}
